package com.zhuiYun.project.api.chat;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zhuiYun.project.api.customer.service.CustomerService;
import com.zhuiYun.project.common.response.CommonResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.CrossOrigin;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Arrays;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @ClassName CustomerWebSocketServer
 * @Description TODO
 * @Author lzy
 * @Date 2023/4/18 14:52
 **/
@ServerEndpoint(value = "/customerWebSocket/{userId}/{role}")
@Component
@CrossOrigin
public class CustomerWebSocketServer {

    /**
     * 记录日志
     */
    private static final Logger log = LoggerFactory.getLogger(WebSocketServer.class);

    /**
     * 用来保存,用户的session
     */
    public static Map<String, Session> sessionUserMap = new ConcurrentHashMap<>();


    /**
     * 用来保存客服的session
     */
    public static Map<String, Session> sessionCustomerMap = new ConcurrentHashMap<>();

    private static CustomerService customerService;

    @Autowired
    public void setMessageService(CustomerService customerService){
        CustomerWebSocketServer.customerService = customerService;
    }

    /**
    * @Description 连接建立成功调用方法
    * @Author lzy
    * @Date 2023/4/18 14:59
    * @Return void
    * @param session
    */
    @OnOpen
    public void onOpen(Session session, @PathParam("userId")String userId, @PathParam("role") Integer role){
        // 判断是客服连接还是用户连接 0是用户连接，1是客服连接
        if (role == 1 || role.equals("1")) {
            sessionCustomerMap.put(userId, session);
        } else {
            sessionUserMap.put(userId, session);
            if (!sessionCustomerMap.isEmpty()) {
                Set<String> strings = sessionCustomerMap.keySet();
                String[] strings1 = strings.toArray(new String[0]);
                int[] array = Arrays.asList(strings1).stream().mapToInt(Integer::parseInt).toArray();
                Random random = new Random();
                Integer inceptId = array[random.nextInt(strings1.length)];
                CommonResult chatRecordByUserId = customerService.getChatRecordByUserId(userId);
                JSONObject entries = new JSONObject();
                entries.set("msg", chatRecordByUserId.getData());
                // 发送人
                entries.set("sender", "");
                // 消息接收人
                entries.set("inceptId", inceptId);
                // 消息内容
                entries.set("context", "请问有什么可以帮到您");
                // 是否有客服在线
                entries.set("customerOnlineFlag", true);
                this.sendMessage(entries.toString(), session);
                // 推送客服新用户
                Session customerSession = sessionCustomerMap.get(inceptId.toString());
                JSONObject jsonObject1 = new JSONObject();
                // 发送人
                jsonObject1.set("sender", userId);
                // 消息接收人
                jsonObject1.set("inceptId", 0);
                // 消息内容
                jsonObject1.set("context", "");
                // 是否有客服在线
                jsonObject1.set("customerOnlineFlag", true);
                this.sendMessage(jsonObject1.toString(), customerSession);
            } else {
                JSONObject entries = new JSONObject();
                // 是否有客服在线
                entries.set("customerOnlineFlag", false);
                this.sendMessage(entries.toString(), session);
            }
        }
    }


    @OnMessage
    public void onMessage(String message,Session session, @PathParam("userId")String userId, @PathParam("role") Integer role){
        Session toSession = null;
        JSONObject jsonObject = JSONUtil.parseObj(message);
        // persons表示发送给哪个用户，比如admin
        String inceptId = jsonObject.getStr("inceptId");
        String sender = jsonObject.getStr("senderId");
        // msg发送的消息文本
        String context = jsonObject.getStr("content");
        if (role == 1 || role.equals("1")) {
            toSession = sessionUserMap.get(inceptId);
        } else {
            toSession = sessionCustomerMap.get(inceptId);
        }

        if (toSession != null) {
            JSONObject jsonObject1 = new JSONObject();
            // 发送人
            jsonObject1.set("sender", sender);
            // 消息接收人
            jsonObject1.set("inceptId", 0);
            // 消息内容
            jsonObject1.set("context", context);
            // 是否有客服在线
            jsonObject1.set("customerOnlineFlag", true);
            this.sendMessage(jsonObject1.toString(), toSession);
        }
    }



    @OnClose
    public void onClose(Session session, @PathParam("userId") String userId, @PathParam("role") Integer role){
        if (role == 1 || role.equals("1")) {
            sessionCustomerMap.remove(userId, session);
        } else {
            sessionUserMap.remove(userId);
        }
    }


    @OnError
    public void onError(Session session,Throwable error,@PathParam("id") String id){

    }

    /**
     * 服务端发送消息给客户端
     * @param message
     * @param toSession
     */
    private void sendMessage(String message, Session toSession) {
        try {
            log.info("服务端给客户端[{}]发送消息{}", toSession.getId(), message);
            toSession.getBasicRemote().sendText(message);
        } catch (Exception e) {
            log.error("服务端发送消息给客户端失败", e);
        }
    }

    /**
    * @Description 服务端发送消息给所有客户端
    * @Author lzy
    * @Date 2023/4/18 14:58
    * @Return void
    * @param message
    */
    private void sendAllMessage(String message){
        try {
            for(Session session : sessionUserMap.values()){
                if (session.isOpen()) {
                    session.getBasicRemote().sendText(message);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }


}
